package cn.agiledata.bank.linkbank.impl.icbc;

import cn.agiledata.bank.linkbank.impl.AbstractBankNetPayRequest;
import cn.agiledata.bank.linkbank.logic.CryptoKeyValidator;
import cn.agiledata.bank.linkbank.logic.DigitalSignGeneratable;

abstract class IcbcNetPayRequest extends AbstractBankNetPayRequest implements
        DigitalSignGeneratable {

    protected String certFilePath;

    protected String keyFilePath;

    protected CryptoKeyValidator cryptoKeyValidator;

    public IcbcNetPayRequest() {
        super();
        this.cryptoKeyValidator = new IcbcCryptoKeyValidator();
        init();
    }

    protected abstract void init();

    public final void setCertFilePath(String certFilePath) {
        this.certFilePath = certFilePath;
    }

    public final void setKeyFilePath(String keyFilePath) {
        this.keyFilePath = keyFilePath;
    }

    public final String getCryptoKeyDescription() {
        return this.cryptoKeyValidator.getCryptoKeyDescription();
    }

    public final boolean validateCryptoKey(String cryptoKey) {
        return this.cryptoKeyValidator.validateCryptoKey(cryptoKey);
    }

    /**
     * 预处理商户URL，以满足工商银行对于商户URL的特殊要求
     * 
     * @param merchantUrl
     *            原始商户URL
     * @return 处理后的商户URL
     */
    protected String handleMerchantUrl(String merchantUrl) {
        // 工商银行只接收http协议的商户url
        merchantUrl = merchantUrl.replaceFirst("https://", "http://");
        // 去掉端口号，工商银行只接受80端口
        int portIndex = merchantUrl.indexOf(":", "http://".length());
        if (portIndex >= 0) {
            int index = merchantUrl.indexOf("/", portIndex);
            if (index > portIndex) {
                merchantUrl = merchantUrl.substring(0, portIndex)
                        + merchantUrl.substring(index);
            } else {
                merchantUrl = merchantUrl.substring(0, portIndex);
            }
        }
        return merchantUrl;
    }

}